package com.ciei.dpagm.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ciei.dpagm.common.enums.ErrorCodeEnum;
import com.ciei.dpagm.common.service.BaseService;
import com.ciei.dpagm.entity.ParameterModel;
import com.ciei.dpagm.entity.ParameterModule;
import com.ciei.dpagm.entity.Users;
import com.ciei.dpagm.mapper.ParameterModelMapper;
import com.ciei.dpagm.util.APP;
import com.ciei.dpagm.util.JsonUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ParameterModelService extends BaseService<ParameterModelMapper, ParameterModel> implements IModelService {

    @Autowired
    private ParameterModuleService parameterModuleService;

    @Autowired
    private ParameterService parameterService;


    /**
     * 组装参数库数据模型列表
     * @param modelList
     * @return
     */
    public JSONArray packageDataList(List<ParameterModel> modelList){
        JSONArray jsonArray = new JSONArray();
        for (ParameterModel parameterModel : modelList){
            JSONObject jsonData = new JSONObject();
            jsonData.put("id",parameterModel.getModelId());
            jsonData.put("propertyName",parameterModel.getPropertyName());
            jsonArray.add(jsonData);
        }
        return jsonArray;
    }

    /**
     * 加载参数库模型模块列表
     * @return
     */
    @Override
    public JSONObject loadModelList(){
        return JsonUtil.getSuccess("").fluentPut(APP.DATA, packageDataList(list()));
    }


    /**
     * 根据名称搜索模型模块数据
     * @param searchName
     * @return
     */
    @Override
    public JSONObject searchDataByName(String searchName){
        JSONObject returnData = new JSONObject();
        List<ParameterModel> modelList = new ArrayList<>();
        List<ParameterModule> moduleList = new ArrayList<>();
        searchDataToList(searchName,modelList,moduleList);
        returnData.fluentPut("modelData",packageDataList(modelList))
                  .fluentPut("moduleData",parameterModuleService.packageDataList(moduleList));
        return JsonUtil.getSuccess("").fluentPut(APP.DATA,returnData);
    }

    public void searchDataToList(String searchName,List<ParameterModel> modelList,List<ParameterModule> moduleList){
        if (StringUtils.isNotBlank(searchName)){
            QueryWrapper<ParameterModel> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().like(ParameterModel::getPropertyName,searchName);
            //搜索二级目录
            List<ParameterModule> parameterModuleList = parameterModuleService.searchListByName(searchName);
            if (!parameterModuleList.isEmpty()){
                moduleList.addAll(parameterModuleList);
                queryWrapper.lambda().or().in(ParameterModel::getModelId,parameterModuleList.stream().map(ParameterModule::getParameterModelId).collect(Collectors.toSet()));
            }
            modelList.addAll(list(queryWrapper));
        }
    }

    /**
     * json数据转成实体
     * @param data  Json数据
     * @return
     */
    public ParameterModel jsonToPojo(JSONObject data){
        ParameterModel parameterModel = new ParameterModel();
        parameterModel.setPropertyName(data.getString("propertyName"));
        return parameterModel;
    }

    /**
     * 根据中文名称查询列表
     * @param propertyName
     * @return
     */
    public List<ParameterModel> getListByPropertyName(String propertyName){
        return findByProperty(ParameterModel::getPropertyName,propertyName);
    }

    /**
     * 添加模型
     * @param webData
     * @return
     */
    @Override
    public JSONObject add(JSONObject webData){
        JSONObject validateResult = validateModelData(webData);
        if (!validateResult.getBoolean(APP.SUCCESS)){
            return validateResult;
        }
        ParameterModel parameterModel = jsonToPojo(webData);
        save(parameterModel);
        return init(parameterModel,null);
    }

    /**
     * 初始化
     * @param parameterModel
     * @return
     */
    public JSONObject init(ParameterModel parameterModel,List<ParameterModule> parameterModuleList){
        JSONObject data = new JSONObject();
        data.fluentPut("id",parameterModel.getModelId())
                .fluentPut("propertyName",parameterModel.getPropertyName() == null ? "" : parameterModel.getPropertyName());
        List<JSONObject> parameterModuleDataList = new ArrayList<>();
        if(parameterModuleList != null){
            for(ParameterModule parameterModule : parameterModuleList){
                JSONObject parameterModuleData = new JSONObject();
                parameterModuleData.fluentPut("id",parameterModule.getModuleId())
                        .fluentPut("propertyName",parameterModule.getPropertyName() == null ? "" : parameterModule.getPropertyName())
                        .fluentPut("pid",parameterModule.getParameterModelId());
                parameterModuleDataList.add(parameterModuleData);
            }
        }
        data.fluentPut("children",parameterModuleDataList);
        return JsonUtil.getSuccess("").fluentPut(APP.DATA,data);
    }

    @Override
    public JSONObject update(JSONObject data) {
        JSONObject validateResult = validateModelData(data);
        if (!validateResult.getBoolean(APP.SUCCESS)){
            return validateResult;
        }
        ParameterModel parameterModel = jsonToPojo(data);
        parameterModel.setModelId(data.getInteger("id"));
        updateById(parameterModel);
        List<ParameterModule> parameterModuleList = parameterModuleService.findByProperty(ParameterModule::getParameterModelId, parameterModel.getModelId());
        return init(parameterModel,parameterModuleList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject delete(JSONObject data) {
        Integer modelId = data.getInteger("id");
        ParameterModel parameterModel = findById(modelId);
        if (parameterModel != null){
            JSONObject deleteResult = parameterModuleService.deleteByModelId(modelId);
            if (!deleteResult.getBoolean(APP.SUCCESS)){
                return deleteResult;
            }
            removeById(modelId);
        }
        return JsonUtil.getSuccess("");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject copy(JSONObject webData, Users user) {
        webData.put("copy","copy");
        JSONObject validateResult = validateModelData(webData);
        if (!validateResult.getBoolean(APP.SUCCESS)){
            return validateResult;
        }
        ParameterModel parameterModel = jsonToPojo(webData);
        save(parameterModel);
        List<ParameterModule> parameterModuleList = parameterModuleService.copyDataThroughModelId(webData.getInteger("id"), parameterModel.getModelId());
        return init(parameterModel,parameterModuleList);
    }


    /**
     * 校验数据
     * @param data
     * @return
     */
    public JSONObject validateModelData(JSONObject data){
        String propertyName = data.getString("propertyName");
        if (StringUtils.isBlank(propertyName)){
            return JsonUtil.getFail(ErrorCodeEnum.INVALID_PARAM);
        }
        Integer modelId = data.getInteger("id");
        if (modelId == null || StringUtils.isNotBlank(data.getString("copy"))){
            if (!getListByPropertyName(propertyName).isEmpty()){
                return JsonUtil.getFail(ErrorCodeEnum.DUPLICATE_DATA,"名称重复,请重新输入!");
            }
        }else {
            ParameterModel oldParameterModel = findById(modelId);
            if (oldParameterModel == null){
                return JsonUtil.getFail(ErrorCodeEnum.DATA_NOT_FOUND);
            }
            if (!getListByPropertyName(propertyName).isEmpty() && !oldParameterModel.getPropertyName().equals(propertyName)){
                return JsonUtil.getFail(ErrorCodeEnum.DUPLICATE_DATA,"名称重复,请重新输入!");
            }
        }
        return JsonUtil.getSuccess("");
    }

    @Override
    public JSONObject export(JSONObject data, HttpServletResponse response) {
        return parameterService.exportByModelId(data.getInteger("id"),response);
    }


}
